package spring.boot.wx.mini.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class ImagesService {

    @Value("${wx-mini.img-sec-check}")
    private String imgSecCheck;

    @Autowired
    private RestTemplate restTemplate;


    public Boolean restCheckPic(MultipartFile file, String accessToken) {
        String url = imgSecCheck.replace("ACCESS_TOKEN",accessToken);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("media",file.getResource());
        org.springframework.http.HttpEntity<MultiValueMap<String, Object>> httpEntity = new org.springframework.http.HttpEntity<>(param, headers);

        JSONObject checkImgObject = null;
        String errcode = null;
        try {
            ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
            checkImgObject = responseEntity.getBody();
            errcode = checkImgObject.getString("errcode");
            log.info("图片验证结果===={}",checkImgObject);
        } catch (Throwable e) {
            log.error("====图片检测违规url访问异常======");
            log.error(e.getMessage(), e);
            return true;
        }

        if ("0".equals(errcode)){
            log.info("图片检测不违规！");
            return true;
        }else if("87014".equals(errcode)){
            log.warn("图片检测违规！");
            return false;
        }else{
            log.error("图片违规检测发生未知异常");
            return true;
        }
    }

}
